const path = require('path');
const authConst = require('../constant/auth-const');

module.exports = options => {
    return async function authHandler(ctx, next) {
        const { url, method } = ctx;
        console.log('authHandler url:', url);
        console.dir({authHandler: 'authHandler', url, method});
        // console.log('authHandler env:', ctx.app.config.env);

        const authToken = ctx.getAuthorization();
        if (!authToken) {
            return ctx.errorResult('token missing');
        }

        try {
            const { username, type, roleId } = ctx.helper.jwtVerify(authToken);
            const cacheToken = await ctx.helper.getRedisStr(`user:${username}`);

            console.log('===================================================================================');
            console.dir({username, type, roleId});
            console.dir([authToken, cacheToken]);
            console.log('===================================================================================');

            if (type === authConst.userType.supremo.value) {
                return await next();
            }

            if (!cacheToken) {
                ctx.errorResult('token expired, please login!');
            } else if (authToken !== cacheToken) {
                ctx.errorResult('token invalid');
            } else {
                const [apiPath] = ctx.url.split('?');
                const [root, api, module, func] = apiPath.split(path.sep);
                console.dir({apiAuth: 'apiAuth', module, func});

                const [apiAuth] = await ctx.helper.checkApiAuthForRole(roleId, module, func);
                if (apiAuth) {
                    await next();
                } else {
                    ctx.errorResult('no access api auth');
                }
            }
        } catch (error) {
            ctx.errorResult(error.message);
        }
    }
};